#!/bin/sh

export E2E_VERSION=1
export E2E_TEST_BEFORE_ALL_FUNCTION="${E2E_TEST_BEFORE_ALL_FUNCTION:-e2e_test_before_all}"
export E2E_TEST_INSTALL_FUNCTION="${E2E_TEST_INSTALL_FUNCTION:-e2e_test_install}"
export E2E_TEST_FUNCTION="${E2E_TEST_FUNCTION:-e2e_test}"
export E2E_BEFORE_RUN_TEST_FUNCTION="${E2E_BEFORE_RUN_TEST_FUNCTION:-e2e_before_run_test}"
export E2E_AFTER_RUN_TEST_FUNCTION="${E2E_AFTER_RUN_TEST_FUNCTION:-e2e_after_run_test}"
export E2E_TEST_UNINSTALL_FUNCTION="${E2E_TEST_UNINSTALL_FUNCTION:-e2e_test_uninstall}"
export E2E_TEST_AFTER_ALL_FUNCTION="${E2E_TEST_AFTER_ALL_FUNCTION:-e2e_test_after_all}"
export E2E_BEFORE_RUN_TEST_COUNT=0
export SPEC_PATH="${SPEC_PATH:-$E2E_PATH/spec}"
export E2E_LOCK
export E2E_TEST_REGISTRY
export E2E_TEST_REGISTRY_PATH
export E2E_HASH_VARIABLES='
    E2E_VERSION
    E2E_ENV
    E2E_COMPONENTS_REGISTRY
    E2E_COMPONENTS_REGISTRY_PATH
    E2E_ENABLE_RESOURCE_REQUIREMENTS
    E2E_EXTENSIONS_REGISTRY_PATH
    E2E_IMAGE_MAP
    E2E_MAJOR_SOURCE_POSTGRES_VERSION
    E2E_MAJOR_TARGET_POSTGRES_VERSION
    E2E_MINOR_SOURCE_POSTGRES_VERSION
    E2E_MINOR_TARGET_POSTGRES_VERSION
    E2E_OPERATOR_REGISTRY
    E2E_OPERATOR_REGISTRY_PATH
    E2E_SET_MAX_LENGTH_NAMES
    E2E_SET_MAX_LENGTH_NAMES_PLUS_ONE
    E2E_SKIP_UPGRADE_FROM_PREVIOUS_OPERATOR
    E2E_STORAGE_CLASS_REFLINK_ENABLED
    E2E_POSTGRES_VERSION
    K8S_VERSION
    STACKGRES_PREVIOUS_VERSION
    STACKGRES_TARGET_VERSION
    '

ESCAPE=$(printf "\033")
NOCOLOR="${ESCAPE}[0m"
RED="${ESCAPE}[91m"
GREEN="${ESCAPE}[92m"
YELLOW="${ESCAPE}[93m"
BLUE="${ESCAPE}[94m"

setup_spec() {
  if [ -n "$STACKGRES_TARGET_VERSION" ] && [ "${STACKGRES_VERSION%.*}" != "${STACKGRES_TARGET_VERSION%.*}" ]
  then
    SPEC_PATH="$E2E_PATH/spec/previous/${STACKGRES_TARGET_VERSION%.*}/spec"
    if [ ! -d "$SPEC_PATH" ]
    then
      echo "Specs for StackGres $STACKGRES_TARGET_VERSION not found"
      exit 1
    fi
    echo "Using spec from $SPEC_PATH for target version $STACKGRES_TARGET_VERSION"
  else
    echo "Using spec from $SPEC_PATH for target version $STACKGRES_TARGET_VERSION"
  fi
}

e2e_test_before_all() {
  true
}

e2e_test_values() {
  echo none
}

e2e_test_install() {
  create_or_replace_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE" "$(e2e_test_install_pods)"

  wait_pods_running "$CLUSTER_NAMESPACE" "$(e2e_test_install_pods)"
  wait_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE"
  switch_cluster_to_first "$CLUSTER_NAME" "$CLUSTER_NAMESPACE"
}

e2e_test_install_pods() {
  echo 1
}

e2e_test() {
  echo "Please, define a test function"
  false
}

e2e_test_uninstall() {
  helm_cleanup_chart "$CLUSTER_NAME" "$CLUSTER_NAMESPACE"

  k8s_async_cleanup_namespace "$CLUSTER_NAMESPACE"
}

e2e_test_after_all() {
  true
}

e2e_exclusive_lock() {
  false
}

e2e_use_extensions() {
  false
}

e2e_test_extra_hash() {
  true
}

get_all_specs() {
  find "$SPEC_PATH" -maxdepth 1 -type f | grep '^.*/[^\.]\+$'
}

get_all_env_specs() {
  if [ -d "$SPEC_PATH/$E2E_ENV" ]
  then
    find "$SPEC_PATH/$E2E_ENV" -maxdepth 1 -type f | grep '^.*/[^\.]\+$'
  fi
}

get_all_exclusive_specs() {
  local SPEC_FILE
  get_all_specs \
    | while IFS="$(printf '\n')" read SPEC_FILE
      do
        (
        . "$SPEC_FILE"
        if e2e_exclusive_lock
        then
          echo_raw "$SPEC_FILE"
        fi
        )
      done
}

get_all_non_exclusive_specs() {
  local SPEC_FILE
  get_all_specs \
    | while IFS="$(printf '\n')" read SPEC_FILE
      do
        (
        . "$SPEC_FILE"
        if ! e2e_exclusive_lock
        then
          echo_raw "$SPEC_FILE"
        fi
        )
      done
}

get_all_exclusive_env_specs() {
  local SPEC_FILE
  get_all_env_specs \
    | while IFS="$(printf '\n')" read SPEC_FILE
      do
        (
        . "$SPEC_FILE"
        if e2e_exclusive_lock
        then
          echo_raw "$SPEC_FILE"
        fi
        )
      done
}

get_all_non_exclusive_env_specs() {
  local SPEC_FILE
  get_all_env_specs \
    | while IFS="$(printf '\n')" read SPEC_FILE
      do
        . "$SPEC_FILE"
        if ! e2e_exclusive_lock
        then
          echo_raw "$SPEC_FILE"
        fi
      done
}

to_e2e_test_batch() {
  local BATCH_INDEX="$1"
  local BATCH_COUNT="$2"
  if ! [ "$BATCH_INDEX" -ge 1 ] && [ "$BATCH_INDEX" -le "$BATCH_COUNT" ]
  then
    echo 'Batch index must start from 1 and must be less or equal than batch count, but it was '"$BATCH_INDEX/$BATCH_COUNT" >&2
    return 1
  fi
  if ! [ "$BATCH_COUNT" -ge 1 ]
  then
    echo 'Batch count must be greather or equal to 1, but it was '"$BATCH_COUNT" >&2
    return 1
  fi
  while IFS="$(printf '\n')" read LINE
  do
    if [ -f "$E2E_PATH/test.stats" ] \
      && grep -q "^${LINE##*spec/}:" "$E2E_PATH/test.stats"
    then
      grep "^${LINE##*spec/}:" "$E2E_PATH/test.stats"
    else
      SPECS_NO_STATS="$SPECS_NO_STATS ${LINE##*spec/}"
      echo "${LINE##*spec/}:3600"
    fi
  done \
    | sort | sort -t : -k 2 -n | grep -n '.' \
    | while IFS="$(printf '\n')" read LINE
      do
        if [ "$(( (${LINE%%:*} - 1) % BATCH_COUNT))" -eq "$((BATCH_INDEX - 1))" ]
        then
          echo "$LINE" | cut -d : -f 2
        fi
      done
}

spec_with_lock() {
  local SPEC_FILE="$1"
  local SPEC_NAME="${SPEC_FILE##*/}"
  flock "$TARGET_PATH/$SPEC_NAME.lock" "$SHELL" $SHELL_XTRACE "$E2E_PATH/e2e" spec "$SPEC_FILE"
}

spec() {
  local RESULT
  local EXIT_CODE
  local SPEC_FILE="$1"
  local SPEC_NAME="${SPEC_FILE##*/}"
  local SPEC_VALUES_FILE="$1.values.yaml"
  local CLUSTER_NAMESPACE="${CLUSTER_NAMESPACE:-$SPEC_NAME-$(printf '%x' "$(date +%s)")}"
  local CLUSTER_NAME
  CLUSTER_NAME="$(get_sgcluster_name "$SPEC_NAME")"
  local E2E_SKIP_SPEC_INSTALL="${E2E_SKIP_SPEC_INSTALL:-false}"
  local E2E_SKIP_SPEC_BEFORE_ALL="${E2E_SKIP_SPEC_BEFORE_ALL:-false}"
  local E2E_SKIP_SPEC_AFTER_ALL="${E2E_SKIP_SPEC_AFTER_ALL:-false}"
  local LOG_PATH="$TARGET_PATH/logs/$SPEC_NAME/$CLUSTER_NAMESPACE"
  local SPEC_TIME="0"
  export SPEC_FILE SPEC_NAME CLUSTER_NAMESPACE CLUSTER_NAME LOG_PATH

  if [ ! -f "$SPEC_FILE" ]
  then
    echo "Spec file $SPEC_FILE was not found"
    return 1
  fi

  mkdir -p "$LOG_PATH"

  if [ ! -f "$SPEC_VALUES_FILE" ]
  then
    SPEC_VALUES_FILE="$SPEC_PATH/default.values.yaml"
  fi

  . "$SPEC_FILE"

  if "${E2E_LOCK:-true}" && e2e_exclusive_lock
  then
    E2E_LOCK=false flock_shell "$TARGET_PATH/exclusive-lock" \
      "$E2E_PATH/e2e" spec "$1"
    return
  fi

  if "${E2E_LOCK:-true}"
  then
    E2E_LOCK=false flock_shared_shell "$TARGET_PATH/exclusive-lock" \
      "$E2E_PATH/e2e" spec "$1"
    return
  fi

  rm -f "$TARGET_PATH/$SPEC_NAME.failed"
  echo -n > "$LOG_PATH/$SPEC_NAME.log"

  trap_exec tail -f "$LOG_PATH/$SPEC_NAME.log" \
    | (
    set +x
    while IFS="$(printf '\n')" read -r line
    do
      echo_raw "$(date +"%Y-%m-%d %H:%M:%S") [$SPEC_NAME] $line"
    done
    ) &

  if ! flock_shell "$TARGET_PATH/check-operator-lock" \
      "$E2E_PATH/e2e" reinstall_operator_if_not_as_expected >> "$LOG_PATH/$SPEC_NAME.log"
  then
    echo "$SPEC_NAME. Operator re-install failed. See file $LOG_PATH/$SPEC_NAME.log for details" > "$TARGET_PATH/$SPEC_NAME.failed"
    echo "$SPEC_NAME. Operator re-install failed. See file $LOG_PATH/$SPEC_NAME.log for details" >> "$TARGET_PATH/logs/results.log"
    return 1
  fi

  echo
  echo "================================================================"
  echo " 🛠️  Running $SPEC_NAME tests"
  echo "================================================================"
  echo

  local START="$(date +%s)"
  try_function run_spec >> "$LOG_PATH/$SPEC_NAME.log" 2>&1
  SPEC_TIME="$(( $(date +%s)-START ))"
  echo "$SPEC_TIME" > "$TARGET_PATH/$SPEC_NAME.duration"
  if ! "$RESULT"
  then
    echo "$SPEC_FILE" > "$TARGET_PATH/$SPEC_NAME.completed"
    echo "$SPEC_FILE" > "$TARGET_PATH/$SPEC_NAME.failed"
    echo "❌ $SPEC_NAME. FAIL. See file $LOG_PATH/$SPEC_NAME.log for details" >> "$TARGET_PATH/logs/results.log"
    if [ "$E2E_SPEC_TRY_UNINSTALL_ON_FAILURE" = "true" ]
    then
      cleanup_spec || true
    fi
    return "$EXIT_CODE"
  fi
  echo "$SPEC_FILE" > "$TARGET_PATH/$SPEC_NAME.completed"
  echo "$SPEC_FILE" > "$TARGET_PATH/$SPEC_NAME.success"
  if [ "$E2E_USE_TEST_CACHE_PER_TEST" = true ]
  then
    store_test_result "$SPEC_NAME"
  fi
  echo "✅ $SPEC_NAME. SUCCESS. Test took $SPEC_TIME seconds" >> "$TARGET_PATH/logs"/results.log
}

run_spec() {
  local FUNCTION
  if [ "$E2E_SKIP_SPEC_BEFORE_ALL" != true ]
  then
    for FUNCTION in $E2E_TEST_BEFORE_ALL_FUNCTION
    do
      "$FUNCTION"
    done
  fi

  if [ "$E2E_SKIP_SPEC_INSTALL" != true ]
  then
    for FUNCTION in $E2E_TEST_INSTALL_FUNCTION
    do
      "$FUNCTION"
    done
  fi

  for SPEC_VALUE in $(e2e_test_values)
  do
    if [ "$SPEC_VALUE" != none ]
    then
      if grep -qxF "$SPEC_NAME.$SPEC_VALUE" "$TARGET_PATH/already-passed-tests"
      then
        echo
        echo "================================================================"
        echo "Skipping $SPEC_NAME.$SPEC_VALUE tests since it is excluded"
        echo "================================================================"
        echo
        continue
      fi
    fi
    for FUNCTION in $E2E_TEST_FUNCTION
    do
      if [ "$SPEC_VALUE" != none ]
      then
        echo
        echo "================================================================"
        echo "Running $SPEC_NAME.$SPEC_VALUE tests"
        echo "================================================================"
        echo
      fi
      "$FUNCTION"
    done
    if [ "$SPEC_VALUE" != none ] \
      && [ "$E2E_USE_TEST_CACHE_PER_TEST" = true ]
    then
      store_test_result "$SPEC_NAME" "$SPEC_VALUE"
    fi
  done

  cleanup_spec
}

cleanup_spec(){
  local FUNCTION
  if [ "$E2E_SKIP_SPEC_UNINSTALL" != true ]
  then
    for FUNCTION in $E2E_TEST_UNINSTALL_FUNCTION
    do
      "$FUNCTION" || true
    done
  fi

  for FUNCTION in $E2E_TEST_AFTER_ALL_FUNCTION
  do
    "$FUNCTION" || true
  done
}

run_test() {
  local FUNCTION
  for FUNCTION in $E2E_BEFORE_RUN_TEST_FUNCTION
  do
    "$FUNCTION"
  done
  local TEST_NAME="$1"
  shift
  echo
  echo "----------------------------------------------------------------"
  echo " ⚙️  Running test $TEST_NAME"
  echo "----------------------------------------------------------------"
  echo
  local RESULT
  local EXIT_CODE
  try_function "$@"
  if ! "$RESULT"
  then
    return "$EXIT_CODE"
  fi
  echo "☑️ $TEST_NAME. SUCCESS."
  for FUNCTION in $E2E_AFTER_RUN_TEST_FUNCTION
  do
    "$FUNCTION"
  done
}

e2e_before_run_test() {
  E2E_BEFORE_RUN_TEST_COUNT="$((E2E_BEFORE_RUN_TEST_COUNT + 1))"
}

e2e_after_run_test() {
  true
}

calculate_spec_hashes() {
  "$SHELL" "$PROJECT_PATH/stackgres-k8s/ci/build/build-functions.sh" generate_image_hashes

  local HELM_MODULE_HASH JVM_IMAGE_MODULE_HASH NATIVE_IMAGE_MODULE_HASH UI_IMAGE_MODULE_HASH
  HELM_MODULE_HASH="$(
    grep '^helm-packages=' "$PROJECT_PATH/stackgres-k8s/ci/build/target/image-hashes.$(cat stackgres-k8s/ci/build/target/build_hash)" \
      | cut -d = -f 2)"
  JVM_IMAGE_MODULE_HASH="$(
    grep '^jvm-image=' "$PROJECT_PATH/stackgres-k8s/ci/build/target/image-type-hashes.$(cat stackgres-k8s/ci/build/target/build_hash)" \
      | cut -d = -f 2)"
  NATIVE_IMAGE_MODULE_HASH="$(
    grep '^native-image=' "$PROJECT_PATH/stackgres-k8s/ci/build/target/image-type-hashes.$(cat stackgres-k8s/ci/build/target/build_hash)" \
      | cut -d = -f 2)"
  UI_IMAGE_MODULE_HASH="$(
    grep '^ui-image=' "$PROJECT_PATH/stackgres-k8s/ci/build/target/image-type-hashes.$(cat stackgres-k8s/ci/build/target/build_hash)" \
      | cut -d = -f 2)"
  local SPEC_PLATFORM
  SPEC_PLATFORM="$("$SHELL" "$PROJECT_PATH/stackgres-k8s/ci/build/build-functions.sh" get_platform_tag_suffix)"
  # shellcheck disable=SC2015
  [ -n "$HELM_MODULE_HASH" ] \
    && [ -n "$JVM_IMAGE_MODULE_HASH" ] \
    && [ -n "$UI_IMAGE_MODULE_HASH" ] \
    && [ -n "$NATIVE_IMAGE_MODULE_HASH" ] \
    && [ -n "$SPEC_PLATFORM" ] \
    && true || false
  "$SHELL" "$PROJECT_PATH/stackgres-k8s/ci/build/build-functions.sh" init_hash
  local VARIABLES_HASH
  VARIABLES_HASH="$(get_variables_for_hash)"
  VARIABLES_HASH="$(printf '%s' "$VARIABLES_HASH" | md5sum | cut -d ' ' -f 1)"
  {
    get_all_specs
    get_all_env_specs
  } | while read SPEC_FILE
      do
        SPEC_NAME="${SPEC_FILE##*/}"
        SPEC_HASH="$( {
          echo "${SPEC_FILE##*spec/}"
          "$SHELL" "$PROJECT_PATH/stackgres-k8s/ci/build/build-functions.sh" path_hash \
              "$(realpath --relative-to "$PROJECT_PATH" "$SPEC_FILE")"
          if [ ! -f "$SPEC_FILE.values.yaml" ]
          then
            "$SHELL" "$PROJECT_PATH/stackgres-k8s/ci/build/build-functions.sh" path_hash \
              "$(realpath --relative-to "$PROJECT_PATH" "$SPEC_PATH/default.values.yaml")"
          fi
          ls -1d "$SPEC_FILE".* 2>/dev/null | sort \
            | while read -r SPEC_SUB_FILE
              do
                if ! [ -f "$SPEC_SUB_FILE" ]
                then
                  continue
                fi
                "$SHELL" "$PROJECT_PATH/stackgres-k8s/ci/build/build-functions.sh" path_hash \
                  "$(realpath --relative-to "$PROJECT_PATH" "$SPEC_SUB_FILE")"
              done
          (
          . "$SPEC_FILE"
          if e2e_use_extensions
          then
            get_extensions_index_hash
          fi
	        e2e_test_extra_hash
          )
          printf '%s\n' "$HELM_MODULE_HASH"
          if [ "${IMAGE_TAG%-jvm}" = "$IMAGE_TAG" ]
          then
            printf '%s\n' "$NATIVE_IMAGE_MODULE_HASH"
          else
            printf '%s\n' "$JVM_IMAGE_MODULE_HASH"
          fi
          if [ "$SPEC_NAME" = ui ]
          then
            printf '%s\n' "$UI_IMAGE_MODULE_HASH"
          fi
          printf '%s' "$VARIABLES_HASH"
        })"
        SPEC_HASH="$(printf '%s' "$SPEC_HASH" | md5sum | cut -d ' ' -f 1)"
        printf '%s:%s-%s\n' "${SPEC_FILE##*spec/}" "$SPEC_HASH" "$SPEC_PLATFORM"
        (
        . "$SPEC_FILE"
        for SPEC_VALUE in $(e2e_test_values)
        do
          if [ "$SPEC_VALUE" != none ]
          then
            printf '%s:%s-%s\n' "${SPEC_FILE##*spec/}.$SPEC_VALUE" "$SPEC_HASH" "$SPEC_PLATFORM"
          fi
        done
        )
      done
}

get_variables_for_hash() {
  env -0 \
    | tr '\n\0' ' \n' | cut -d = -f 1 | sort | uniq \
    | while read -r NAME
      do
        if [ x != "x$NAME" ] && echo " $(echo "$E2E_HASH_VARIABLES" | tr '\n' ' ' | tr -s ' ') " | grep -qF " $NAME "
        then
          eval "[ x = \"x\$$NAME\" ] || printf '%s=%s\n' \"$NAME\" \"\$$NAME\""
        fi
      done
}

get_already_passed_tests() {
  [ -n "$E2E_TEST_REGISTRY" ] \
    && [ -n "$E2E_TEST_REGISTRY_PATH" ] \
    && true || false

  "$SHELL" "$PROJECT_PATH/stackgres-k8s/e2e/e2e" calculate_spec_hashes \
    > "$TARGET_PATH/test-hashes"
  while read -r SPEC_HASH
  do
    SPEC_NAME="${SPEC_HASH%:*}"
    SPEC_HASH="${SPEC_HASH#*:}"
    printf '%s=%s/%s/e2e-test-result-%s:%s\n' \
      "$SPEC_NAME" "$E2E_TEST_REGISTRY" "$E2E_TEST_REGISTRY_PATH" "$SPEC_NAME" "$SPEC_HASH"
  done < "$TARGET_PATH/test-hashes" \
    > "$TARGET_PATH/test-result-images"

  cut -d = -f 2- "$TARGET_PATH/test-result-images" \
    > "$TARGET_PATH/all-test-result-images"

  "$SHELL" "$PROJECT_PATH/stackgres-k8s/ci/build/build-functions.sh" find_image_digests \
    "$TARGET_PATH/all-test-result-images" \
    > "$TARGET_PATH/test-result-image-digests"

  rm -f "$TARGET_PATH/already-passed-tests"
  touch "$TARGET_PATH/already-passed-tests"
  if [ "$E2E_DO_TESTS" != true ]
  then
    local SPEC_NAME
    while IFS='=' read -r SPEC_NAME IMAGE_NAME
    do
      if grep -q "^$IMAGE_NAME=" "$TARGET_PATH/test-result-image-digests"
      then
        printf '%s\n' "$SPEC_NAME" >> "$TARGET_PATH/already-passed-tests"
      fi
    done < "$TARGET_PATH/test-result-images"
  fi

  tr '\n' ' ' < "$TARGET_PATH/already-passed-tests"
}

store_test_results() {
  E2E_SUFFIX="${E2E_SUFFIX:-$(printf '%s%x-%s' - "$(date +%s)" "$(random_string_lowercase 3)")}"

  [ -n "$E2E_TEST_REGISTRY" ] \
    && [ -n "$E2E_TEST_REGISTRY_PATH" ] \
    && true || false

  sort "$TARGET_PATH/runned-tests" 2>/dev/null | uniq > "$TARGET_PATH/uniq-runned-tests"
  sort "$TARGET_PATH/passed-tests" 2>/dev/null | uniq > "$TARGET_PATH/uniq-passed-tests"

  local SPEC_PLATFORM
  SPEC_PLATFORM="$("$SHELL" "$PROJECT_PATH/stackgres-k8s/ci/build/build-functions.sh" get_platform_tag_suffix)"
  # shellcheck disable=SC2046
  docker image registry.access.redhat.com/ubi8-micro:8.8-7 > /dev/null 2>&1 \
    || docker pull registry.access.redhat.com/ubi8-micro:8.8-7
  while read -r SPEC_NAME
  do
    IMAGE_NAME="$(grep "^$SPEC_NAME=" "$TARGET_PATH/test-result-images" \
      | cut -d = -f 2-)"
    docker tag registry.access.redhat.com/ubi8-micro:8.8-7 "$IMAGE_NAME"
    docker push "$IMAGE_NAME"
  done < "$TARGET_PATH/uniq-passed-tests"
}

store_test_result() {
  local SPEC_NAME="$1"
  local SPEC_VALUE="$2"

  [ -n "$E2E_TEST_REGISTRY" ] \
    && [ -n "$E2E_TEST_REGISTRY_PATH" ] \
    && true || false

  local SPEC_PLATFORM
  SPEC_PLATFORM="$("$SHELL" "$PROJECT_PATH/stackgres-k8s/ci/build/build-functions.sh" get_platform_tag_suffix)"
  local IMAGE_NAME
  if [ -z "$SPEC_VALUE" ]
  then
    IMAGE_NAME="$(grep "^$SPEC_NAME=" "$TARGET_PATH/test-result-images")"
   else
    IMAGE_NAME="$(grep "^$SPEC_NAME.$SPEC_VALUE=" "$TARGET_PATH/test-result-images")"
  fi
  IMAGE_NAME="$(printf %s "$IMAGE_NAME" | cut -d = -f 2-)"
  # shellcheck disable=SC2046
  docker image registry.access.redhat.com/ubi8-micro:8.8-7 > /dev/null 2>&1 \
    || docker pull registry.access.redhat.com/ubi8-micro:8.8-7
  docker tag registry.access.redhat.com/ubi8-micro:8.8-7 "$IMAGE_NAME"
  docker push "$IMAGE_NAME"
}

add_already_passed_tests_to_report() {
  E2E_ALREADY_PASSED_COUNT="$(wc -l "$TARGET_PATH/already-passed-tests" | cut -d ' ' -f 1)"

  cat << EOF > "$TARGET_PATH/already-passed-e2e-tests-junit-report.xml"
<?xml version="1.0" encoding="UTF-8"?>
<testsuites time="0">
  <testsuite name="e2e tests already passed" tests="$E2E_ALREADY_PASSED_COUNT" time="0">
    $(
      while read -r TEST_NAME
      do
        if ! grep -qxF "$TEST_NAME" "$TARGET_PATH/all-tests"
        then
          continue
        fi
        TEST_HASH="$(grep "^$TEST_NAME:" "$TARGET_PATH/test-hashes")"
        TEST_HASH="${TEST_HASH#*:}"
        cat << INNER_EOF
    <testcase classname="$TEST_NAME" name="$TEST_HASH" time="0" />
INNER_EOF
      done < "$TARGET_PATH/already-passed-tests"
      )
  </testsuite>
</testsuites>
EOF
}

show_test_result_summary() {
  local EXIT_CODE="${1:-0}"

  local TEST_NAME
  local ANY_TEST_ALREADY_PASSED=false
  while read -r TEST_NAME
  do
    if grep -qxF "$TEST_NAME" "$TARGET_PATH/all-tests"
    then
      ANY_TEST_ALREADY_PASSED=true
      break
    fi
  done < "$TARGET_PATH/already-passed-tests"
  if [ "$ANY_TEST_ALREADY_PASSED" = true ]
  then
    echo "${BLUE}Already passed tests${NOCOLOR}:"
    echo
    while read -r TEST_NAME
    do
      if grep -qxF "$TEST_NAME" "$TARGET_PATH/all-tests"
      then
        printf ' - %s\n' "$TEST_NAME"
      fi
    done < "$TARGET_PATH/already-passed-tests"
    echo
  else
    echo "No test where cached before for this build"
    echo
  fi

  sort "$TARGET_PATH/runned-tests" 2>/dev/null | uniq > "$TARGET_PATH/uniq-runned-tests"
  sort "$TARGET_PATH/passed-tests" 2>/dev/null | uniq > "$TARGET_PATH/uniq-passed-tests"

  if [ -s "$TARGET_PATH/uniq-passed-tests" ]
  then
    echo "${GREEN}Passed tests${NOCOLOR}:"
    echo
    while read -r TEST_NAME
    do
      printf ' - %s\n' "$TEST_NAME"
    done < "$TARGET_PATH/uniq-passed-tests"
    echo
  elif [ "$({ wc -l "$TARGET_PATH/uniq-runned-tests" 2>/dev/null || echo '0'; } | cut -d ' ' -f 1)" != \
    "$({ wc -l "$TARGET_PATH/uniq-passed-tests" 2>/dev/null || echo '0'; } | cut -d ' ' -f 1)" ]
  then
    echo "${YELLOW}Passed tests${NOCOLOR}:"
    echo
    echo "None :("
    echo
  fi

  if [ "$({ wc -l "$TARGET_PATH/uniq-runned-tests" 2>/dev/null || echo '0'; } | cut -d ' ' -f 1)" != \
    "$({ wc -l "$TARGET_PATH/uniq-passed-tests" 2>/dev/null || echo '0'; } | cut -d ' ' -f 1)" ]
  then
    echo "${RED}Failed tests${NOCOLOR}:"
    echo
    while read -r TEST_NAME
    do
      if ! grep -qxF "$TEST_NAME" "$TARGET_PATH/uniq-passed-tests"
      then
        printf ' - %s\n' "$TEST_NAME"
      fi
    done < "$TARGET_PATH/uniq-runned-tests"
    echo
  else
    if [ "$EXIT_CODE" != 0 ]
    then
      echo "Something went bad?! 😢"
    else
      echo "Everything went well! 😀"
    fi
    echo
  fi
}
